package com.cloud.common.filter;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.cors.reactive.CorsUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * 功能描述: 网关跨域处理
 *
 * @author yzj
 */
@Configuration
public class GlobalCorsFilter {

    @Bean
    public WebFilter corsFilter() {
        return (ServerWebExchange webExchange, WebFilterChain chain) -> {
            ServerHttpRequest request = webExchange.getRequest();
            // 判断当前请求是否跨域
            if (!CorsUtils.isCorsRequest(request)) {
                return chain.filter(webExchange);
            }
            HttpHeaders reqHeaders = request.getHeaders();
            ServerHttpResponse response = webExchange.getResponse();
            // 获取请求方式对象
            HttpMethod reqMethod = reqHeaders.getAccessControlRequestMethod();
            HttpHeaders headers = response.getHeaders();
            // 把请求头中的请求源(协议+ip+端口)添加到响应头中
            headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, reqHeaders.getOrigin());
            headers.addAll(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, reqHeaders.getAccessControlRequestHeaders());
            if (reqMethod != null) {
                // 允许被响应的方法(GET/POST等)
                headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, reqMethod.name());
            }
            // 允许在请求中携带cookie
            headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
            // 允许在请求中携带的头信息
            headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "*");
            // 本次跨域检测的有效期(单位毫秒)
            headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "18000L");
            // 直接给option请求反回结果
            if (request.getMethod() == HttpMethod.OPTIONS) {
                response.setStatusCode(HttpStatus.OK);
                return Mono.empty();
            }
            return chain.filter(webExchange);
        };
    }

}
